<?php

class MetaClass {
	private $__classname;
	private function __construct($classname){ $this->__classname=$classname; }
	public function GetClassName(){ return $this->__classname; }

	private $__table;
	public function SetDBTableName($value){ $this->__table = $value; }
	public function GetDBTableName(){ return $this->__table; }

	private $__orderby = null;
	public function SetOrderBy($value){ $this->__orderby = $value; }
	public function GetOrderBy(){ return $this->__orderby; }

	private $__abstract_dbfield_name = null;
	public function SetAbstractDBFieldName($value){ $this->__abstract_dbfield_name = $value; }
	public function GetAbstractDBFieldName(){ return $this->__abstract_dbfield_name; }
	public function IsAbstract(){ return !is_null($this->__abstract_dbfield_name); }

	private $__parent = null;
	public function SetParentMetaClass($parent){ $this->__parent = $parent; }
	public function GetParentMetaClass(){ return $this->__parent; }
	public function GetRootMetaClass(){ return is_null($this->__parent) ? $this : $this->GetParentMetaClass()->GetRootMetaClass(); }

	public function Compile(){
		foreach ($this as $key=>$value){
			if ($value instanceof MetaField || $value instanceof MetaSlave) {
				$value->SetMetaClass($this);
				$value->SetName($key);
				if ($value->GetLabel() == null) $value->WithLabel(Lemma::Retrieve($this->__classname.$key));
			}
		}
	}
	

	public function GetMetaFields(){
		$r = array();
		foreach ($this as $key=>$value){
			if (!($value instanceof MetaField)) continue;
			$r[$key] = $value;
		}
		return $r;
	}

	public function GetDBFields(){
		$r = array();
		foreach ($this as $key=>$value){
			if (!($value instanceof MetaField)) continue;
			if ($value->IsVolatile()) continue;
			$r[$key] = $value;
		}
		return $r;
	}

	public function GetMetaSlaves(){
		$r = array();
		foreach ($this as $key=>$value){
			if (!($value instanceof MetaSlave)) continue;
			$r[$key] = $value;
		}
		return $r;
	}

	public function GetDBSlaves(){
		$r = array();
		foreach ($this as $key=>$value){
			if (!($value instanceof MetaSlave)) continue;
			if ($value->IsVolatile()) continue;
			$r[$key] = $value;
		}
		return $r;
	}

	private static $cache = array();
	public static function Retrieve($classname){
		if (!array_key_exists($classname,self::$cache)) {
			$c = new MetaClass($classname);
			$m = new ReflectionMethod($classname,'FillMetaClass');
			$m->invoke(null,$c);
			$c->Compile();
			self::$cache[$classname] = $c;
		}
		return self::$cache[$classname];
	}
}



?>